package com.tanhua.dubbo.api;

import com.tanhua.domain.sound.SoundCount;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.http.ResponseEntity;

import java.util.List;

/**
 * @author To my left is the dog
 * @date 2021/2/28 17:00
 */
@Service
public class SoundCountApiImpl implements SoundCountApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(SoundCount soundCount) {
        soundCount.setId(new ObjectId());
        soundCount.setCreated(System.currentTimeMillis());
        mongoTemplate.save(soundCount);
    }

    @Override
    public SoundCount findById(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        SoundCount soundCount = mongoTemplate.findOne(query, SoundCount.class);
        return soundCount;
    }

    /*修改剩余次数*/
    @Override
    public void update(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId).and("remainingTimes").ne(0));
        SoundCount soundCount = mongoTemplate.findOne(query, SoundCount.class);

        Update update = new Update();
        update.inc("remainingTimes", -1);
        mongoTemplate.updateFirst(query, update, SoundCount.class);
    }

    @Override
    public void update() {
        Query query = new Query();
        List<SoundCount> soundCountList = mongoTemplate.find(query, SoundCount.class);
        for (SoundCount soundCount : soundCountList) {
            query=new Query(Criteria.where("_id").is(soundCount.getId()));
            Update update = new Update();
            update.set("remainingTimes", 10);
            mongoTemplate.updateFirst(query, update, SoundCount.class);
        }
    }
}
